<template>
  <div class="auditor-pick-wrap">
    <div v-for="(item, index) in tagSelecteds" :key="item.id" :style="{ height: showMobilePage ? 'auto' : '24px'}" class="pick-item">
      <span v-if="item.userName">{{ item.userName }}</span>
      <span v-else>{{ item.departmentName }}({{ item.peopleNum }}人)</span>
      <i v-if="['ContractProcessEdit', 'ContractProcessEditCustom'].includes($route.name) || !item.lock" class="el-icon-close close-btn" @click="deleteBtn(item, index)" />
    </div>
    <div class="search-input">
      <el-select
        v-loadmore="loadMoreUser"
        v-if="!isDefaultList"
        ref="elSelectRef"
        v-model="state"
        :append-to-body="true"
        :remote-method="filterData"
        popper-class="my-auditor-pick-autocomplete"
        placeholder="搜索姓名"
        filterable
        remote
        size="small"
        class="user-select filterableSelect remoteRequest1"
        @hook:mounted="cancalReadOnly"
        @visible-change="cancalReadOnly"
        @change="handleSelect">
        <div slot="empty" style="display: flex; height: 34px; width: 293px; justify-content: center; align-items: center; color: #999">
          无数据
        </div>
        <el-option
          v-for="(item, index) in list.items"
          :key="index"
          :value="item"
          style="height: 66px; width: 293px;">
          <div class="user-info-box">
            <el-avatar :size="40" :src="item.avatar" style="min-width: 40px" @error="errorHandler">
              <img :src="adminIcon" alt="avatar">
            </el-avatar>
            <div class="user-info">
              <span class="name">{{ item.userName }}</span>
              <span class="post">{{ returnDept(item, 'post') }}</span>
              <span :title="returnDept(item, 'dept')" class="dept ellipsisOne" style="max-width: 180px">{{ returnDept(item, 'dept') }}</span>
            </div>
          </div>
        </el-option>
        <div v-if="isLoading" class="loading-container"><i class="el-icon-loading"/></div>
      </el-select>
      <el-select
        v-else
        v-model="state"
        popper-class="my-auditor-pick-autocomplete"
        placeholder="选择用户"
        size="small"
        class="user-select filterableSelect remoteRequest1 hideIcon"
        @change="handleSelect">
        <div slot="empty" style="display: flex; height: 34px; width: 293px; justify-content: center; align-items: center; color: #999">
          无数据
        </div>
        <el-option
          v-for="(item, index) in defaultUserList"
          :key="index"
          :value="item"
          style="height: 66px; width: 293px;">
          <div class="user-info-box">
            <el-avatar :size="40" :src="item.avatar" @error="errorHandler">
              <img :src="adminIcon" alt="icon">
            </el-avatar>
            <div class="user-info">
              <span class="name">{{ item.userName }}</span>
              <span class="post">{{ returnDept(item, 'post') }}</span>
            </div>
          </div>
        </el-option>
      </el-select>
    </div>
  </div>
</template>
<script>
// import { getUserList } from '@/api/user';
import { getAuditorList, getAuditorButtonList } from '@/api/legal';
import adminIcon from '@/assets/user-avatar.png';
import { dfsDept } from './utils';
import { mapState } from 'vuex';
export default {
  name: 'AuditorPick',
  props: {
    selectedAuditors: { // 最终选择的审批人
      type: Array,
      default: () => {
        return [];
      }
    },
    tagSelecteds: { // 显示的tag数据
      type: Array,
      default: () => {
        return [];
      }
    },
    isSubmitBtn: { // 入口是否从自定义提交按钮处来
      type: Boolean,
      default: false
    },
    extendParams: {
      type: Object,
      default: null
    },
    examineRoleId: {
      type: String | Number,
      default: ''
    },
    max: {
      type: Number,
      default: 0
    },
    isDefaultList: { // 是否不进行搜索直接使用传进来的值
      type: Boolean,
      default: false
    },
    includeLeaver: { // 是否包含已离职人员
      type: Number,
      default: 0
    },
    defaultUserList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      state: '',
      adminIcon,
      keyword: '',
      isLoading: false,
      queryForm: {
        examineRoleId: '',
        name: ''
      },
      list: {
        items: [],
        total: null,
        page: 0,
        perPage: 0
      }
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'showMobilePage': state => state.app.showMobilePage
    }),
    auditorIds() {
      const temp = this.selectedAuditors.map(item => item.id);
      return temp;
    }
  },
  methods: {
    // 返回用户部门
    returnDept(item, key) {
      if (item[key]) {
        const value = item[key];
        return value;
      } else {
        return '--';
      }
    },
    errorHandler() {
      return true;
    },
    handleSelect(val) {
      const { id, userName, avatar, post } = val;
      if (this.auditorIds.indexOf(id) >= 0) {
        this.$message({
          type: 'warning',
          message: '不能重复选择'
        });
        return;
      }
      if (this.auditorIds.length >= this.max) {
        this.$message({
          type: 'warning',
          message: '选择超过限制'
        });
        return;
      }
      const tempTagSelecteds = JSON.parse(JSON.stringify(this.tagSelecteds));
      const tempSelectedAuditors = JSON.parse(JSON.stringify(this.selectedAuditors));
      const param = {
        id,
        userName,
        avatar,
        post
      };
      tempTagSelecteds.push(param);
      tempSelectedAuditors.push(param);
      this.$emit('update:tagSelecteds', tempTagSelecteds);
      this.$emit('update:selectedAuditors', tempSelectedAuditors);
      this.list = {
        items: [],
        total: null,
        page: 0,
        perPage: 0
      };
    },
    deleteBtn(item, index) {
      const tempTagSelecteds = JSON.parse(JSON.stringify(this.tagSelecteds));
      this.deleteStaff(item);
      tempTagSelecteds.splice(index, 1);
      this.$emit('update:tagSelecteds', tempTagSelecteds);
    },
    // 取消选择后 审批人选择列表 删除 该部门下人员
    deleteStaff(item) {
      const { userId, id } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectedAuditors));
      if (item.isDepartment) {
        const staffs = dfsDept(item, []);
        while (staffs.length) {
          const cur = staffs.pop();
          const selectUserIds = tempSelectUsers.map(jitem => jitem.id);
          const deleteIndex = selectUserIds.indexOf(cur.id);
          if (deleteIndex >= 0) {
            tempSelectUsers.splice(deleteIndex, 1);
          }
        }
        this.$emit('update:selectedAuditors', tempSelectUsers);
      } else {
        const selectUserIds = tempSelectUsers.map(jitem => jitem.id);
        let deleteIndex;
        if (userId) {
          deleteIndex = selectUserIds.indexOf(userId);
        } else {
          if (id) deleteIndex = selectUserIds.indexOf(id);
        }
        if (deleteIndex >= 0) {
          tempSelectUsers.splice(deleteIndex, 1);
          this.$emit('update:selectedAuditors', tempSelectUsers);
        }
      }
    },
    filterData(val) {
      this.keyword = val;
      if (val === '') {
        this.list = {
          items: [],
          total: null,
          page: 0,
          perPage: 0
        };
      } else {
        this.getUserMethods(1, val);
      }
    },
    getUserMethods(page, name) {
      const param = {
        examineRoleId: this.examineRoleId,
        name: name,
        page,
        perPage: 20
      };
      this.isLoading = true;
      if (this.extendParams) {
        Object.keys(this.extendParams).forEach(key => {
          param[key] = this.extendParams[key];
        });
      }
      if (this.includeLeaver) {
        param.includeLeaver = 1;
      }
      const getUser = this.getUserList();
      getUser(param).then(res => {
        this.isLoading = false;
        if (res.code === 200) {
          if (page > 1 && this.list.items) {
            const concatList = this.list.items.concat(res.data.items);
            res.data.items = concatList;
            this.list = res.data;
          } else {
            this.list = res.data;
          }
        }
      }).catch((err) => {
        if (err.code === 503) { // 503 表示流程状态已变更
          this.$emit('refresh');
        }
        console.log(err);
        this.isLoading = false;
      });
    },
    getUserList() {
      const isSubmitBtn = this.isSubmitBtn;
      if (!isSubmitBtn) {
        return getAuditorList;
      } else {
        return getAuditorButtonList;
      }
    },
    loadMoreUser() {
      const list = this.list;
      const currentPage = list.page;
      if (list.items) {
        if (list.items.length < list.total && !this.isLoading) {
          this.getUserMethods(currentPage + 1, this.keyword);
        }
      }
    },
    cancalReadOnly(onOff) {
      if (this.showMobilePage) {
        this.$nextTick(() => {
          if (!onOff) {
            const { elSelectRef } = this.$refs;
            const input = elSelectRef.$el.querySelector('.el-input__inner');
            input.removeAttribute('readonly');
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.auditor-pick-wrap {
  height: 476px;
  margin-bottom: 24px;
  @include scrollBar($width: 4px);
  .pick-item {
    display: inline-block;
    line-height: 24px;
    margin-right: 8px;
    margin-bottom: 8px;
    padding: 0 6px;
    font-size: 12px;
    color: #333;
    background-color: #f5f5f5;
    border-radius: 2px;
    .close-btn {
      cursor: pointer;
    }
  }
  .search-input {
    display: inline-block;
    position: relative;
  }
  & ::v-deep {
    .el-input__inner {
      height: 24px;
      line-height: 24px;
      border: none;
      padding: 0 8px 0 0;
      font-size: 12px;
      width: 80px;
      &::-webkit-input-placeholder {
        color: #999;
      }
    }
    /* .hideIcon {
      .el-input__suffix {
        display: none;
      }
    } */
    .el-input__suffix {
      display: none;
    }
  }
}
.user-info-box {
  display: flex;
  padding-top: 12px;
  .user-info {
    display: flex;
    flex: 1;
    height: 54px;
    flex-direction: column;
    margin-left: 8px;
    border-bottom: 1px solid #EBEEFD;
    .name {
      color: #333333;
      font-weight: bold;
      font-size: 14px;
      margin-bottom: 4px;
      line-height: 1;
    }
    .post {
      color: #666;
      font-size: 12px;
      line-height: 1;
      margin-bottom: 4px;
    }
    .dept {
      color: #999;
      font-size: 12px;
      line-height: 1;
      height: 1.2em;
    }
  }
  ::v-deep .el-avatar{
    img{
      width: 100% !important;
      height: 100% !important;
    }
  }
}
.loading-container {
  display: flex;
  justify-content: center;
}
</style>
<style lang="scss">
.my-auditor-pick-autocomplete {
  .el-select-dropdown__wrap {
    max-height: 408px;
  }
  .el-select-dropdown__item {
    padding: 0 12px;
  }
}
</style>
